package com.wzq.controller.admin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.service.IFavoritesService;
import com.wzq.util.StringUtil;
import com.wzq.dao.pojo.Favorites;
import com.wzq.dao.pojo.PageBean;
import com.wzq.dao.pojo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/favorites")
public class AdminFavoritesController extends GetSome {

    @Autowired
    private IFavoritesService iFavoritesService;
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        String query=pageBean.getQuery().trim();
        Page<Favorites> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<Favorites> pageResult = iFavoritesService.page(page, new QueryWrapper<Favorites>().in(StringUtil.isNotEmpty(query), "w_id", searchByWname(query)));
        //        添加用户名称和项目名称
        List<Favorites> list=new ArrayList<>();
        for (Favorites favorites : pageResult.getRecords()) {
            favorites.setW_name( getW_name(favorites.getW_id()) );
            favorites.setP_name( getP_name(favorites.getP_id()) );
            list.add(favorites);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("FavoritesList",pageResult.getRecords());
        map.put("total",pageResult.getTotal());

        return R.ok(map);
    }

    @RequestMapping("/save")
    public R save(@RequestBody Favorites favorites){
        if(favorites.getId()==null || favorites.getId()==-1){
            iFavoritesService.save(favorites);
        }else{
            iFavoritesService.saveOrUpdate(favorites);
        }
        return R.ok();
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        Favorites favorites = iFavoritesService.getById(id);
        //        获得用户名称和项目名称
        favorites.setW_name( getW_name(favorites.getW_id()) );
        favorites.setP_name( getP_name(favorites.getP_id()) );
        Map<String,Object> map=new HashMap<>();
        map.put("favorites",favorites);
        return R.ok(map);
    }

    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id){
        iFavoritesService.removeById(id);
        return R.ok();
    }
}
